<!-- 移动端资源分配 -->
<template>
  <section>
    <div
      style="margin-bottom: 10px;background-color: white;padding: 10px;text-align: left;"
    >
      <span>当前选择用户：{{ currentTokenUser.user.name }}</span>
      <el-button type="primary" @click="newGroup" style="margin-left: 10px;"
        >新增资源组</el-button
      >
    </div>
    <el-row :gutter="10">
      <el-col :span="10">
        <div class=" bg">
          <el-scrollbar>
            <draggable @change="sortData" v-model="userApps" :animation="340">
              <transition-group>
                <div
                  v-for="item in userApps"
                  :key="item.id"
                  style="padding: 10px;border-bottom: 1px solid #dfdfdf;"
                >
                  <div class="panel_title">
                    <div style="font-weight: bold;">{{ item.name }}</div>
                    <div>
                      <el-button
                        type="text"
                        style="margin-left: 20px"
                        @click="addGroupRes(item)"
                        >分配资源</el-button
                      >
                      <el-button
                        type="text"
                        style="margin-left: 20px"
                        @click="editGroup(item)"
                        >编辑组</el-button
                      >
                      <el-button
                        type="text"
                        style="margin-left: 20px"
                        @click="delGroup(item)"
                        >删除组</el-button
                      >
                    </div>
                  </div>
                  <div>
                    <getResource ref="resourceList" :group="item"></getResource>
                  </div>
                </div>
              </transition-group>
            </draggable>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="14">
        <div class=" bg">
          <el-scrollbar>
            <div class="panel_title">
              <span style="font-weight: bold;">该用户-所有已分配资源</span>
              <el-button type="primary" @click="showNoOpenResDialog"
                >分配不公开资源</el-button
              >
            </div>
            <div class="app_container">
              <div v-for="(v, i) in pageData" :key="i" class="chart-wrapper">
                <div class="current current-normal">
                  <img draggable="false" :src="getImg(v.icon)" alt="暂无图片" />
                  <span>{{ v.name }}</span>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      :visible.sync="appResourceStatus"
      v-if="appResourceStatus"
      title="移动端资源组-分配资源"
      class="app_res_dialog"
      width="1024px"
    >
      <group-set-resource
        ref="resource"
        :groupId="groupId"
        :type="1"
        :user-id="userId"
      />

      <div slot="footer">
        <el-button type="primary" @click="saveResource">确定</el-button>
        <el-button @click="appResourceStatus = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showAddGroupDialog"
      v-if="showAddGroupDialog"
      :title="groupTitle"
      class="app_group_dialog"
      width="600px"
    >
      <el-form label-width="100px">
        <el-form-item label="组名称">
          <el-input v-model="groupForm.name"></el-input>
        </el-form-item>
        <el-form-item label="组描述">
          <el-input type="textarea" v-model="groupForm.description"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="groupForm.sn"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="saveGroup">确定</el-button>
        <el-button @click="showAddGroupDialog = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- no -->
    <el-dialog
      :visible.sync="showNoOpenRes"
      v-if="showNoOpenRes"
      title="分配不公开资源"
      class="app_res_dialog"
      width="1024px"
    >
      <div v-if="noOpenRes.length == 0">
        <div style="text-align:center;color:#c1c1c1">
          暂无可分配资源
        </div>
      </div>
      <div v-else>
        <p>
          <el-checkbox v-model="checkAll" @change="selectAll2"
            >全选</el-checkbox
          >
        </p>
        <div class="app_container">
          <div v-for="(v, i) in noOpenRes" :key="i.id" class="chart-wrapper">
            <div
              class="current"
              :class="v.active ? 'current-active' : 'current-normal'"
              @click="changeItem(v)"
            >
              <img draggable="false" :src="getImg(v.icon)" alt="暂无图片" />
              <span>{{ v.name }}</span>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="saveNoOpenRes">确定</el-button>
        <el-button @click="showNoOpenRes = false">取消</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import draggable from "vuedraggable";
import groupSetResource from "./groupSetResource";
import getResource from "./getResourceList";

export default {
  name: "appResource",
  created() {
    this.getResourceGroup();
  },
  mounted() {
    this.initData();
  },
  props: {
    type: {
      type: Number,
      default: 0
    }
  },
  computed: {},
  watch: {
    //监听pageData下active来改变checkAll
    checkAll(val) {
      this.noOpenRes.map(i => {
        i.active = val;
      });
    }
  },
  data() {
    return {
      noOpenRes: [],
      groupId: "",
      groupForm: {},
      groupTitle: "新增资源组",
      showAddGroupDialog: false, // 新增和修改资源组弹框控制
      showNoOpenRes: false, // 控制不公开资源分配弹框
      appResourceStatus: false,
      userApps: [],
      pageData: [],
      openResData: [], // 公开
      noOpenResData: [], // 不公开
      currentArr: [],
      currentArr2: [],
      checkAll: false,
      userId: "",
      currentGroup: {},
      currentTokenUser: { user: { name: "" } }
    };
  },
  methods: {
    sortData() {
      let ids = [];
      this.userApps.map(item => {
        ids.push(item.id);
      });
      console.log(ids);
      this.API.softResourceGroup({ ids }).then(ret => {
        console.log("排序成功");
      });
    },
    selectAll2(active) {
      this.noOpenRes.map(item => {
        item.active = active;
        if (active) {
          !this.currentArr2.includes(item.id) && this.currentArr2.push(item.id);
        } else {
          this.currentArr2 = [];
        }
      });
    },
    changeItem(item) {
      item.active = !item.active;
      if (item.active && !this.currentArr2.includes(item.id)) {
        this.currentArr2.push(item.id);
      } else {
        let index = this.currentArr2.findIndex(v => v === item.id);
        this.currentArr2.splice(index, 1);
      }
      if (this.currentArr2.length == 0) {
        this.checkAll = false;
      }
      this.$forceUpdate();
    },
    /**
     * @desc 获取资源组列表
     * @time 2021/4/30
     */
    getResourceGroup() {
      this.API.getResourceGroupPageList().then(ret => {
        let group = [];
        ret.data.records.map(item => {
          if (this.$route.query.userId == item.relationUserId) {
            group.push(item);
          }
        });
        this.userApps = group;
      });
    },
    /**
     * @desc 弹出-分配不公开资源弹出
     * @time 2021/4/30
     */
    showNoOpenResDialog() {
      this.showNoOpenRes = true;
      this.API.getResourceAppIdsByUserId({
        userId: this.$route.query.userId
      }).then(ret => {
        let { data } = ret;
        console.log(data);
        if (data.length !== 0) {
          data.map(item => {
            this.$set(item, "active", true);
          });
          this.noOpenRes = data;
        }
      });
    },
    /**
     * @desc 保存-分配不公开资源弹出
     * @time 2021/4/30
     */
    saveNoOpenRes() {
      let body = {
        userId: this.$route.query.userId,
        resourceIds: this.currentArr2
      };
      if (this.currentArr2.length !== 0) {
        this.API.addResourceAppUser({ body }).then(ret => {
          console.log(ret.data);
          this.success("添加成功");
        });
      }
    },
    /**
     * @desc 获取用户详情
     * @time 2021/4/30
     */
    getUserDetail() {
      if (!this.$route.query.userId) {
        return;
      }
      this.API.getUserDetail({ userId: this.$route.query.userId }).then(ret => {
        this.currentTokenUser = ret.data;
      });
    },
    /**
     * @desc 弹出新增资源组
     * @time 2021/4/30
     */
    newGroup() {
      this.groupForm = {
        sn: 0
      };
      this.showAddGroupDialog = true;
      this.groupTitle = "新增资源组";
    },
    /**
     * @desc 弹出组-分配资源
     * @time 2021/4/30
     */
    addGroupRes(item) {
      this.currentGroup = item;
      this.groupId = item.id;
      this.appResourceStatus = true;
    },
    /**
     * @desc 编辑资源组
     * @time 17:11
     */
    editGroup(item) {
      this.showAddGroupDialog = true;
      this.groupTitle = "修改资源组";
      this.API.getResourceGroupById({ id: item.id }).then(ret => {
        console.log(ret.data);
        this.groupForm = ret.data;
      });
    },
    /**
     * @desc 删除资源组
     * @time 2021/4/30
     */
    async delGroup(item) {
      let confirm = await this.confirmForm("是否确认删除资源组！");
      if (confirm === "cancel") return;
      this.API.deleteResourceGroupById({ id: item.id }).then(data => {
        this.success("操作成功");
        // todo 刷新左侧组
        this.getResourceGroup();
      });
    },

    /**
     * @desc 保存资源组信息
     * @time 2021/5/6
     */
    saveGroup() {
      let tem = Object.assign(
        {
          relationUserName: this.currentTokenUser.user.name,
          relationUserId: this.$route.query.userId
        },
        this.groupForm
      );
      this.API.addOrUpdateResourceGroup({ body: tem }).then(data => {
        this.getResourceGroup();
        this.showAddGroupDialog = false;
        this.success("保存成功");
      });
    },
    /**
     * 描述：移动端资源分配确认
     * 时间： 2021/4/24
     */
    saveResource() {
      let body = {
        resourceGroup: this.currentGroup,
        resourceIds: this.$refs.resource.currentArr
      };
      this.API.updateResourceAndUserResource({ body }).then(data => {
        this.$message.success("保存成功");
        this.appResourceStatus = false;
        let findGroup = this.$refs.resourceList.find(item => {
          return item.group.id == this.currentGroup.id;
        });
        findGroup.getData();
      });
    },
    getImg(val) {
      return window.api.image + "/" + val;
    },

    /**
     * 描述：全选框 事件
     * 时间： 2021/4/24
     */
    selectAll(active) {
      this.pageData.map(item => {
        item.active = active;
        if (active) {
          !this.currentArr.includes(item.id) && this.currentArr.push(item.id);
        } else {
          this.currentArr = [];
        }
      });
    },

    /**
     * 描述：获取移动端资源列表及用户选中资源
     * 时间： 2021/4/24
     */
    initData() {
      this.userId = this.$route.query.userId;
      this.getUserDetail();
      let tem = { pageSize: 1000 };
      this.API.getResourceAppPageList(tem).then(ret => {
        this.pageData = ret.data.records;
        this.API.getResourceAppIdsByUserId({
          userId: this.$route.query.userId
        }).then(ret => {
          let data = ret.data;
          this.pageData.map(item => {
            // 返回数据为空的话 pageData下active都设为false currentArr为[]
            this.$set(
              item,
              "active",
              data.length == 0 ? false : data.includes(item.id)
            );
            this.currentArr = data.length == 0 ? [] : data;
          });
        });
      });
    }
  },
  components: { draggable, groupSetResource, getResource }
};
</script>
<style scoped lang="scss">
.bg {
  background-color: white;
  padding: 10px;
}

.panel_title {
  cursor: move;
  display: flex;
  justify-content: space-between;
}

.app_container {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;

  .chart-wrapper {
    display: flex;
    justify-content: center;
    width: 20%;
    padding: 10px 0;

    .current {
      width: 60px;
      height: 50px;
      border-radius: 10px;
      padding: 5px;
      display: flex;
      cursor: pointer;
      flex-direction: column;
      align-items: center;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;

      img {
        width: 30px;
      }

      span {
        letter-spacing: 1px;
        opacity: 0.9;
        margin-top: 5px;
        font-size: 12px;
      }
    }

    .current-active {
      background-color: #f4faff;
      /*color: #409eff;*/
      border: 3px dashed #409eff;
    }

    .current-normal {
      background-color: #f4faff;
      border: 3px dashed #ffffff;
    }
  }
}
</style>
